#include "head.hpp"
static const uint16_t port = 8080;
int pipe_fd[2];
void func(int num)
{
    write(pipe_fd[1], "123", 3);
}
int main(int argc, char *argv[])
{
    pipe(pipe_fd);
    if (fork() != 0)
    {
        signal(2, func);
        wait(nullptr);
        exit(0);
    }
    setpgid(0, 0);
    status_t status;
    init_status(&status, 4);
    init_thread(&status);
    int socket_fd;
    init_socket(&socket_fd, port);
    int epoll_fd = epoll_create(1);
    add_epoll(epoll_fd, socket_fd);
    add_epoll(epoll_fd, pipe_fd[0]);
    while (true)
    {
        struct epoll_event events[2];
        memset(events, 0, sizeof(events));
        int epoll_num = epoll_wait(epoll_fd, events, 2, -1);
        for (int i = 0; i < epoll_num; i++)
        {
            int fd = events[i].data.fd;
            if (fd == socket_fd)
            {
                int net_fd = accept(socket_fd, nullptr, nullptr);
                pthread_mutex_lock(&status.lock);
                enQueue(&status.queue, net_fd);
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);
            }
            else if (fd == pipe_fd[0])
            {
                // // v1
                // char buffer[1024] = {0};
                // read(pipe_fd[0], buffer, sizeof(buffer));
                // printf("信号过来 \n");
                // for (int i = 0; i < 4; i++)
                // {
                //     pthread_cancel(status.thread[i]);
                // }
                // for (int i = 0; i < 4; i++)
                // {
                //     pthread_join(status.thread[i], nullptr);
                // }
                // pthread_exit(nullptr);
                // v2
                pthread_mutex_lock(&status.lock);
                status.exit_flag = 1;
                pthread_cond_broadcast(&status.cond);
                pthread_mutex_unlock(&status.lock);
                for (int i = 0; i < 4; i++)
                {
                    pthread_join(status.thread[i], nullptr);
                }
                pthread_exit(nullptr);
            }
        }
    }
    return 0;
}